package com.mic.nio;

import com.mic.nio.pool.NioSelectorRunnablePool;
import com.mic.nio.pool.Worker;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Executor;

/**
 * Created by yjq14 on 2018/2/10.
 */
public class NioServerWorker extends AbstractNioSelector implements Worker{
    public  NioServerWorker(Executor executor, String threadName, NioSelectorRunnablePool nioSelectorRunnablePool) {
        super(executor, threadName, nioSelectorRunnablePool);
    }

    @Override
    public void registerNewChannelTask(SocketChannel channel) {
        Selector selector = this.selector;
        registerTask(() -> {
            try {
                channel.register(selector, SelectionKey.OP_READ);
            } catch (ClosedChannelException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    protected int select(Selector selector) throws IOException {
        return selector.select();
    }

    @Override
    protected void process(Selector selector) throws IOException {
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        if (selectionKeys.isEmpty()) return;
        Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator();
        while (iterator.hasNext()) {
            SelectionKey s = iterator.next();
            iterator.remove();
            SocketChannel channel = (SocketChannel) s.channel();
            int ret = 0;
            boolean failure = true;
            ByteBuffer buff = ByteBuffer.allocate(1024);
            try {
                ret = channel.read(buff);
                failure = false;
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ret <= 0 || failure) {
                s.cancel();
                System.out.println("客户端连接断开");
            } else {
                System.out.println("收到的数据：" + new String(buff.array()));
            }

            ByteBuffer byteBuffer = ByteBuffer.wrap("收到\n".getBytes());
            channel.write(byteBuffer);
        }
    }
}
